﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CNotebook;
using CNotebook.Manufacturing;
using CNotebook.Inventory;
using NotebookS2.Manufacturing.Dialog;

namespace NotebookS2
{
    public partial class ManufacturingOrder : Form
    {
        public ManufacturingOrder()
        {
            InitializeComponent();
        }
            
        public string ConnectionString { get; set; }
        public string ActiveUserId { get; set; }

        public DataTable LineItems { get; set; }

        void InitializeSeries()
        {

            string ObjectType = "500";
            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();


            if (oSeries.IsAutoNumber(ObjectType) == true)
            {
                txtMONumber.Properties.ReadOnly = true;
                txtMONumber.Text = "##########";

            }
            oSeries.Close();



        }

        string GetNewSeries()
        {
            string _SERIES = "";
            string _OBJECT_TYPE = "500";

            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();
            if (oSeries.IsAutoNumber(_OBJECT_TYPE) == true)
            {
                _SERIES = oSeries.GetNewSeries(_OBJECT_TYPE);
            }
            else
            {
                _SERIES = txtMONumber.Text;
            }
            oSeries.Close();

            return _SERIES;
        }

        public void PrintPreview()
        {
            NotebookS2.Manufacturing.Layout.PRNT_MO oForm = new Manufacturing.Layout.PRNT_MO();

            oForm.ConnectionString = this.ConnectionString;
            oForm.DocumentNumber = txtMONumber.Text;
            oForm.WindowState = FormWindowState.Maximized;
            oForm.ShowDialog();
        }

        public void ShowSearch()
        {
            FND_MO oForm = new FND_MO();
            oForm.ConnectionString = this.ConnectionString;
            oForm.ShowDialog();

            MBRManager oManager = new MBRManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            DataTable dtMOHeader = oManager.GetManufacturingOrder(oForm.SelectedDocumentNumber);
            DataRow oRow = dtMOHeader.Rows[0];

            txtMONumber.Text = oRow["DocNum"].ToString();
            cboProductionType.EditValue = oRow["ProductionType"].ToString();
            txtProductCode.Text = oRow["ProductCode"].ToString();
            txtProductDscription.Text = oRow["ProductDescription"].ToString();
            txtBatchNumber.Text = oRow["BatchNum"].ToString();

            BindProductStructure(txtProductCode.Text);

            txtOrderQty.Text = oRow["OrderQty"].ToString();
            txtServedQty.Text = oRow["ServedQty"].ToString();
            txtUoM.Text = oRow["UnitMeasure"].ToString();
            txtDocStatus.Text = oRow["DocStatus"].ToString();
            dtDateNeeded.EditValue = Convert.ToDateTime(oRow["DateNeeded"].ToString());
            cboReceivingWarehouse.EditValue = oRow["WhseCode"].ToString();
            cboProductStructure.EditValue = oRow["ProductStructure"].ToString();

            dtDateCreated.EditValue = Convert.ToDateTime(oRow["DateCreated"].ToString());
            txtCreatedBy.Text = oRow["CreatedBy"].ToString();
            dtDateModified.EditValue = Convert.ToDateTime(oRow["DateModified"].ToString());
            txtModifiedBy.Text = oRow["ModifiedBy"].ToString();


            this.LineItems = oManager.GetMaterials(txtMONumber.Text);

            gridControl1.DataSource = this.LineItems;
            gridControl1.Refresh();

            btnAdd.Text = "Update";
        }

        void BindWarehouse()
        {
            WarehouseManager oManager = new WarehouseManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();
            DataTable oTable = new DataTable();

            oTable = oManager.GetWarehouse();

            cboReceivingWarehouse.Visible = false;
            cboReceivingWarehouse.Properties.DataSource = oTable;
            cboReceivingWarehouse.Properties.DisplayMember = "Dscription";
            cboReceivingWarehouse.Properties.ValueMember = "Code";
            DevExpress.XtraEditors.Controls.LookUpColumnInfo col;

            col = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Dscription", "Dscription", 100);

            col.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;

            cboReceivingWarehouse.Properties.Columns.Add(col);
            cboReceivingWarehouse.Properties.ShowHeader = false;
            cboReceivingWarehouse.Visible = true;
            oManager.Close();
        }

        void BindItemWarehouse()
        {
            WarehouseManager oManager = new WarehouseManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();
            DataTable oTable = new DataTable();

            oTable = oManager.GetWarehouse();

            
            cboWarehouse.DataSource = oTable;
            cboWarehouse.DisplayMember = "Dscription";
            cboWarehouse.ValueMember = "Code";
            DevExpress.XtraEditors.Controls.LookUpColumnInfo col;

            col = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Dscription", "Dscription", 100);

            col.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;

            cboWarehouse.Columns.Add(col);
            oManager.Close();
        }

        void BindProductStructure(string _ItemCode)
        {
            BOMManager oManager = new BOMManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();
            DataTable oTable = new DataTable();

            oTable = oManager.GetItemProductStructure(_ItemCode);

            cboProductStructure.Visible = false;
            cboProductStructure.Properties.DataSource = oTable;
            cboProductStructure.Properties.DisplayMember = "BOMCode";
            cboProductStructure.Properties.ValueMember = "BOMCode";

            cboProductStructure.Properties.Columns.Clear();
            DevExpress.XtraEditors.Controls.LookUpColumnInfo col;

            col = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("BOMCode", "BOMCode", 100);

            col.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;

            cboProductStructure.Properties.Columns.Add(col);

            DevExpress.XtraEditors.Controls.LookUpColumnInfo colName;

            colName = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("BOMName", "BOMName", 100);

            colName.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;

            cboProductStructure.Properties.Columns.Add(colName);

            cboProductStructure.Properties.ShowHeader = false;
            cboProductStructure.Visible = true;
            oManager.Close();
        }

        DataTable GetLineItems()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("DocNum", typeof(string));
            dt.Columns.Add("ItemGroup", typeof(string));
            dt.Columns.Add("WhseCode", typeof(string));
            dt.Columns.Add("WhseName", typeof(string));
            dt.Columns.Add("ItemCode", typeof(string));
            dt.Columns.Add("Dscription", typeof(string));
            dt.Columns.Add("BaseQty", typeof(double));
            dt.Columns.Add("QtyRequirement", typeof(double));
            dt.Columns.Add("ActualQty", typeof(double));
            dt.Columns.Add("UnitCost", typeof(double));

            return dt;

        }


        private void ManufacturingOrder_Load(object sender, EventArgs e)
        {
            InitializeSeries();
            this.LineItems = GetLineItems();

            cboProductionType.SelectedIndex = 0;
            txtCreatedBy.Text = this.ActiveUserId;
            dtDateCreated.EditValue = System.DateTime.Now;
            txtModifiedBy.Text = this.ActiveUserId;
            dtDateModified.EditValue = System.DateTime.Now;


            dtDateNeeded.EditValue = System.DateTime.Now;

            BindWarehouse();
            BindItemWarehouse();

            gridControl1.DataSource = this.LineItems;
            gridControl1.Refresh();
        }

        private void txtProductCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_ITM_PRD_ONLY oFindItemForm = new FND_ITM_PRD_ONLY();
            
            oFindItemForm.ConnectionString = this.ConnectionString;
            
            oFindItemForm.ShowDialog();

            string sItemCode = oFindItemForm.SelectedItemCode;

            if (sItemCode != null)
            {
                ItemManager oManager = new ItemManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                DataTable oTable = oManager.GetItemMasterData(sItemCode);
                oManager.Close();



                txtProductCode.Text = oTable.Rows[0]["ItemCode"].ToString();
                txtProductDscription.Text = oTable.Rows[0]["Description"].ToString();
                txtUoM.Text = oTable.Rows[0]["InvtyUntMsr"].ToString();


                BindProductStructure(txtProductCode.Text);

            }
        }

        private void cboProductStructure_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                BOMManager oManager = new BOMManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                DataTable dt = oManager.GetMaterials(cboProductStructure.EditValue.ToString(), Convert.ToDouble(txtOrderQty.Text));
                oManager.Close();

                this.LineItems = dt;
                gridControl1.DataSource = this.LineItems;
                gridControl1.Refresh();
            }
            catch { }
            
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {

            MBRManager oManager = new MBRManager();
            MBRUnit oUnit = new MBRUnit();

         
            if (btnAdd.Text == "Add")
            {
                #region Data Header

                txtMONumber.Text = GetNewSeries();
                oUnit.DocumentNumber = txtMONumber.Text;
                oUnit.ProductionType = cboProductionType.Text;
                oUnit.ProductCode = txtProductCode.Text;
                oUnit.ProductDescription = txtProductDscription.Text;
                oUnit.BatchNumber = txtBatchNumber.Text;
                oUnit.QtyOrder = txtOrderQty.Text;
                oUnit.QtyServed = txtServedQty.Text;
                oUnit.UoM = txtUoM.Text;
                oUnit.DocumentStatus = txtDocStatus.Text;
                oUnit.DateNeeded = Convert.ToDateTime(dtDateNeeded.EditValue);
                oUnit.WarehouseCode = cboReceivingWarehouse.EditValue.ToString();
                oUnit.WarehouseName = cboReceivingWarehouse.Text.ToString();
                oUnit.ProductStructure = cboProductStructure.Text;

                oUnit.DateCreated = Convert.ToDateTime(dtDateCreated.EditValue);
                oUnit.CreatedBy = txtCreatedBy.Text;
                oUnit.DateModified = Convert.ToDateTime(dtDateModified.EditValue);
                oUnit.ModifiedBy = txtModifiedBy.Text;

                oUnit.MOLineItems = this.LineItems;
                #endregion

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                SqlException ex = oManager.AddOrder(oUnit);
                oManager.Close();

                if (ex != null)
                {
                    MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                btnAdd.Text = "Update";
            }
            else
            {

                #region Data Header
                oUnit.DocumentNumber = txtMONumber.Text;
                oUnit.ProductionType = cboProductionType.Text;
                oUnit.ProductCode = txtProductCode.Text;
                oUnit.ProductDescription = txtProductDscription.Text;
                oUnit.BatchNumber = txtBatchNumber.Text;
                oUnit.QtyOrder = txtOrderQty.Text;
                oUnit.QtyServed = txtServedQty.Text;
                oUnit.UoM = txtUoM.Text;
                oUnit.DocumentStatus = txtDocStatus.Text;
                oUnit.DateNeeded = Convert.ToDateTime(dtDateNeeded.EditValue);
                oUnit.WarehouseCode = cboReceivingWarehouse.EditValue.ToString();
                oUnit.WarehouseName = cboReceivingWarehouse.Text.ToString();
                oUnit.ProductStructure = cboProductStructure.Text;

                oUnit.DateCreated = Convert.ToDateTime(dtDateCreated.EditValue);
                oUnit.CreatedBy = txtCreatedBy.Text;
                oUnit.DateModified = Convert.ToDateTime(dtDateModified.EditValue);
                oUnit.ModifiedBy = txtModifiedBy.Text;

                oUnit.MOLineItems = this.LineItems;
                #endregion

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                SqlException ex = oManager.UpdateOrder(oUnit);
                oManager.Close();

                if (ex != null)
                {
                    MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                btnAdd.Text = "Update";
            }
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }

        private void txtOrderQty_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                BOMManager oManager = new BOMManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                DataTable dt = oManager.GetMaterials(cboProductStructure.EditValue.ToString(), Convert.ToInt16(txtOrderQty.Text));
                oManager.Close();

                this.LineItems = dt;

                gridControl1.DataSource = this.LineItems;
                gridControl1.Refresh();
            }
            catch { }
        }

        private void cboWarehouse_EditValueChanged(object sender, EventArgs e)
        {
            
        }

        private void cboWarehouse_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            try
            {
                gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["WhseCode"], e.NewValue);

                string _SelectedWhseCode = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["WhseCode"]).ToString();
                string _SelectedItemCode = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["ItemCode"]).ToString();
                double _OnHandStocks = 0;
                StockManager oManager = new StockManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                _OnHandStocks = oManager.GetAvailableQuantity(_SelectedWhseCode, _SelectedItemCode);
                oManager.Close();

                gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["ActualQty"], _OnHandStocks);

            }
            catch
            {
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnIssueToProduction_Click(object sender, EventArgs e)
        {
            NotebookS2.Inventory.Transactions.IssuanceToProduction oForm = new Inventory.Transactions.IssuanceToProduction();

            oForm.MdiParent = this.MdiParent;
            oForm.ConnectionString = this.ConnectionString;
            oForm.LineItems = this.LineItems;
            oForm.Show();

        }
    }
}
